package com.ants.boot.core.security.service;

import com.ants.boot.core.security.user.LoginUser;
import com.ants.boot.system.domain.SysUser;
import com.ants.boot.system.dto.sysuser.AddUserDto;
import com.ants.boot.system.service.SysRoleService;
import com.ants.boot.system.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 蚂蚁会花呗
 * @date 2022/2/15 15:42
 * 手机号登录实现类
 * 这里手机号和普通账号放在了同一个表中
 * 可根据业务讲表进行拆分，不同登录方式
 */
@Service
public class PhoneUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;



    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username){
        SysUser sysUser = sysUserService.findByPhoneNumber(username);
        if (sysUser == null){
            //手机号登录时，如果不存在，这里创建一个账号和手机号一样的记录
            AddUserDto dto = new AddUserDto();
            dto.setUsername(username);
            dto.setPassword(new BCryptPasswordEncoder().encode("123456"));
            dto.setNickName(username);
            dto.setPhoneNumber(username);
            SysUser result = sysUserService.addUser(dto);
            sysUser = new SysUser();
            BeanUtils.copyProperties(result,sysUser);
        }
        List<String> roleList = sysRoleService.findByUserId(sysUser.getId());
        List<GrantedAuthority> authorities = roleList.stream()
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        LoginUser loginUser = new LoginUser(username,sysUser.getPassword(),authorities);
        loginUser.setUserId(sysUser.getId());
        loginUser.setUsername(sysUser.getUsername());
        loginUser.setAge(sysUser.getAge());
        loginUser.setAvatar(sysUser.getAvatar());
        loginUser.setEmail(sysUser.getEmail());
        loginUser.setNickName(sysUser.getEmail());
        loginUser.setPhoneNumber(sysUser.getPhoneNumber());
        return loginUser;
    }
}
